<?php

namespace Apps\AppApi\Method\BeautyParlor;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\BeautyParlor as BeautyParlorModel;
use Apps\Common\Models\BeautyParlorComment;
use Apps\Common\Models\BeautyParlorPhotos;
use Apps\Common\Models\BeautyParlorService;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\BpFavorites;
use Apps\Common\Models\BeautyParlorAttr;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\BeautyParlorTag;
use Phalcon\Mvc\Model;
use Apps\Common\Models\BeautyParlorBrowseLog;
use Apps\Common\Models\BeautyParlorInteractive;
use Apps\Common\Models\UserBase;

/**
 * 
 * 根据美容院ID获取美容院详情
 * 并根据user_id 验证是否关注
 * @author      545
 * @date        2016年1月13日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class BeautyParlor extends BaseMethod
{
    /**
     * @var array
     */
    private $parlor = [];

    public function run()
    {
        $id = intval($this->getDataItem('id',0));
		$user_id = intval($this->getDataItem('user_id',0));
        if(0 < $id) {
            /**
             * 查询基础信息
             */
            $info = BeautyParlorModel::query()
                ->columns([
                    'bp_id as id',
                    'bp_name as name',
                    'bp_cover as cover',
                    'bp_address as address',
                    'bp_tel as tel',
                    'bp_medal as medal',
                    'bp_intro as intro',
                    'X(bp_coordinate) latitude',
                    'Y(bp_coordinate) longitude',
                    'bpa.open_time',//每日开始营业时间
                    'bpa.close_time',//每日停止营业时间
                    'bpa.low_price',//起步价
                    'bpa.open_year',//开业年限
                    'bpa.shop_area',//店铺面积
                    'bpa.service_num',//服务项目多少项
                    'bpa.facilities'//设备设施
                ])
                ->leftJoin('Apps\Common\Models\BeautyParlorAttr','Apps\Common\Models\BeautyParlor.bp_id = bpa.beauty_parlor_id','bpa')
                ->where('Apps\Common\Models\BeautyParlor.bp_state>0 and Apps\Common\Models\BeautyParlor.bp_id=:id:')
                ->bind(['id' => $id])
                ->execute()->getFirst();
        } else {
            return $this->errorLog(ResultStatus::URL_PARAM_CANNOT_EMPTY, '参数异常');
        }
        
        if($info){
            $this->parlor['id'] = $info->id;
            $this->parlor['name'] = $info->name;
            $this->parlor['cover'] = PicUrl::BeautyParlorCover($info->cover, $this->getDi());
            $this->parlor['address'] = $info->address;
            $this->parlor['tel'] = $info->tel;
            $this->parlor['intro'] = $info->intro;
            $this->parlor['latitude'] = $info->latitude;
            $this->parlor['longitude'] = $info->longitude;
            $this->parlor['medal_refund'] = \Apps\Common\Libs\BeautyParlor::getMedalRefund($info->medal);
            $this->parlor['medal_verify'] = \Apps\Common\Libs\BeautyParlor::getMedalVerify($info->medal);
            
            $this->parlor['open_time'] = $info->open_time ==null?'':$info->open_time;
            $this->parlor['close_time'] = $info->close_time ==null?'':$info->close_time;
            $this->parlor['low_price'] = $info->low_price ==null?'':$info->low_price;
            $this->parlor['open_year'] = $info->open_year == null?'':$info->open_year;
            $this->parlor['shop_area'] = $info->shop_area ==null?'':$info->shop_area;
            $this->parlor['service_num'] = $info->service_num==null?0:$info->service_num;
            $this->parlor['facilities'] = $info->facilities==null?[]:(json_decode($info->facilities)?:[]);

            $this->parlor['pics'] = [];

            $this->parlor['services'] = [];

            /**
             * 增加图片列表
             */
            $pics = BeautyParlorPhotos::query()
            ->columns(['photo_url url'])
            ->where('photo_state>0 and beauty_parlor_id=:bid:')
            ->bind(['bid'=>$id])
            ->execute()->toArray();
            foreach($pics as $pic) {
                $this->parlor['pics'][] = PicUrl::BeautyParlorPic($pic['url'], $this->getDi());
            }
            // 如果深度验店 
            if ($this->parlor['medal_verify']){
                
                /**
                 * 增加服务范围列表
                 */
                $service = BeautyParlorService::query()
                ->columns([
                    'service_id id',
                    'service_cover cover',
                    'service_name name',
                    'service_price price',
                    'service_unit unit',
                    'service_description description'])
                ->where('service_state>0 and service_is_sell = 1 and beauty_parlor_id=:bid:')
                ->bind(['bid'=>$id])
                ->limit(10,0)
                ->execute()->toArray();
                    
                foreach($service as $d) {
                    $d['cover'] = PicUrl::BeautyParlorCover($d['cover'], $this->getDi());
                    $unit = $d['unit'];
                    unset($d['unit']);
                    $d['price_show'] = '';
                    if($d['price'] > 0) {
                        $d['price_show'] = $d['price'] . '元' . ($unit ? '/' . $unit : '');
                    }
                    $this->parlor['services'][] = $d;
                }
            }
            
            /**
             * 增加tag列表
             */
            $tag = BeautyParlorTag::query()
                    ->columns([
                        'i.tag_title'
                    ])
                    ->leftJoin('Apps\Common\Models\BeautyParlorTagInfo','Apps\Common\Models\BeautyParlorTag.tag_id = i.tag_id','i')
                    ->where('i.tag_state=1 and bp_id=:bid:')
                    ->bind(['bid' => $id])
                    ->orderBy('sort desc,bp_tag_addtime asc')
                    ->execute()->toArray();
            $this->parlor['tags'] = $tag;
            
            //2.0.1版本新增美粒互动列表，展示3条数据 查询4条数据，方便前端判断是否有更多数据
            $interactive = BeautyParlorInteractive::query()
                            ->columns(['id,content,pics,user_id,addtime'])
                            ->where("bp_id = {$id} AND state = 1")
                            ->orderBy('addtime desc')
                            ->limit(4,0)
                            ->execute()->toArray();
            
            //处理图片
            foreach ($interactive as $k => $val) {
            
                $InteractiveLists[$k]['content'] = unserialize(base64_decode($val['content'])) ?: $val['content'];
                if (json_decode($val['pics'], true)) {
                    $question_pics = PicUrl::Question(json_decode($val['pics'], true), $this->getDi());
                    $interactive[$k]['pics'] = $question_pics;
                }else {
                    $interactive[$k]['pics'] = [];
                }
            
            }
            //设置互动值
            $this->parlor['bp_interactives'] = $interactive;
            $bossid = $interactive[0]['user_id'];
            //查询美容院老板账号信息
            $bossinfo = UserBase::query()
                        ->columns(['user_id,user_nickname,user_gender,user_cover,persional_sign'])
                        ->where("user_id = :bid:")
                        ->bind(['bid'=>$bossid])
                        ->execute()->getFirst();
            if ($bossinfo){
                $bossinfo=$bossinfo->toArray();
                $bossinfo['user_cover'] = PicUrl::UserCover($bossinfo['user_cover'], $this->getDi());
                $bossinfo['persional_sign'] = $bossinfo['persional_sign'] ? unserialize(base64_decode($bossinfo['persional_sign'])) : '';
            }
            else {
                $bossinfo=null;
            }
            $this->parlor['bp_bossinfo'] = $bossinfo;
             
            // 评论总数
            $this->parlor['comment_num'] = BeautyParlorComment::count(
                [
                    'conditions' => 'beauty_parlor_id = :bid: and comment_state = 1',
                    'bind' => [
                        'bid' => $id,
                    ]
                ]
            );
            
            //获取3条评论
            $comments = BeautyParlorComment::query()
                                        ->columns(['u.user_id',
                                            'u.user_nickname',
                                            'u.user_cover',
                                            'u.user_gender',
                                            'u.user_expert',
                                            'Apps\Common\Models\BeautyParlorComment.comment_id as comment_id',
                                            'Apps\Common\Models\BeautyParlorComment.comment_info as comment_info',
                                            'Apps\Common\Models\BeautyParlorComment.comment_photos as comment_photos',
                                            'Apps\Common\Models\BeautyParlorComment.comment_floor as comment_floor',
                                            'Apps\Common\Models\BeautyParlorComment.comment_addtime as addtime'])
                                        ->leftJoin('Apps\Common\Models\UserBase',
                                            'Apps\Common\Models\BeautyParlorComment.user_id=u.user_id','u')
                                        //->where('beauty_parlor_id='.$bp_id)//原代码
                                        ->where('Apps\Common\Models\BeautyParlorComment.beauty_parlor_id='.$id.' and Apps\Common\Models\BeautyParlorComment.comment_state = 1')//修改处
                                        ->orderBy('Apps\Common\Models\BeautyParlorComment.comment_addtime desc')
                                        ->limit(3,0)
                                        ->execute()->toArray();
        foreach($comments as $arr) {
            $arr['user_cover'] = PicUrl::UserCover($arr['user_cover'], $this->getDi());
            $arr['comment_photos'] = PicUrl::BeautyParlorComment(json_decode($arr['comment_photos']), $this->getDi());
            if(unserialize(base64_decode($arr['comment_info']))){
                $arr['comment_info'] = unserialize(base64_decode($arr['comment_info']));
            }
            $data[] = $arr;
        }
        $this->parlor['comments'] = $data;
        }else{
            return $this->errorLog(ResultStatus::QUERY_DATA_NOT_EXIST, 'ID不存在');
        }
        $this->parlor['favorite_num']=BpFavorites::count([
            'conditions' => "bp_id = ".$this->parlor['id'],
        ]);
        if($user_id !=''){
	        $is_favorite=BpFavorites::findFirst("user_id = $user_id and bp_id =".$this->parlor['id']);
	        /* var_dump($is_favorite);
	        exit; */
	        if($is_favorite){
	        	$this->parlor['is_favorite']=1;//已关注
	        }else{
	        	$this->parlor['is_favorite']=0;//未关注
	        }
        }else{
        	$this->parlor['is_favorite']=0;
        }
        //增加浏览记录
        $bplog = new BeautyParlorBrowseLog();
        $bplog->beauty_parlor_id = $this->parlor['id'];
        $bplog->createtime = date("Y-m-d H:i:s", time());
        $bplog->save();
        
        $this->setResult($this->parlor);
    }

}